import { combineReducers } from 'redux';
import { RECEIVE_STATE, ADD_PRAISE } from '../actions/index';

const commentsById = (state = {}, action) => {
  switch (action.type) {
    case RECEIVE_STATE:
      return {
        ...state,
        ...action.data.reduce((obj, comment) => {
          const { id } = comment;
          const newObj = Object.assign({}, obj);
          newObj[id] = comment;
          return newObj;
        }, {}),
      };
    case ADD_PRAISE: {
      const { id } = action;
      const { praise, mpraise } = state[id];
      const willAdd = (mpraise === 0);
      const newPraise = () => (praise > 0 ? (praise - 1) : 0);
      return {
        ...state,
        [id]: {
          ...state[id],
          mpraise: willAdd ? 1 : 0,
          praise: willAdd ? (praise + 1) : newPraise(),
        },
      };
    }
    default:
      return state;
  }
};
const commentsByOrder = (state = [], action) => {
  switch (action.type) {
    case RECEIVE_STATE: {
      console.log(state);
      const order = action.data.map(({ id }) => id);
      return order;
    }
    default:
      return state;
  }
};

export default combineReducers({
  commentsById,
  commentsByOrder,
});
